<template>
    <div class="videos">
        <div class="container">
            <SingleVideo :videoInfo="first" @startRecord="startRecord" @cancelRecord="cancelRecord"
                         @cancelVideo="cancelVideo" :videoIndex="0"/>
            <SingleVideo :videoInfo="second" @startRecord="startRecord" @cancelRecord="cancelRecord"
                         @cancelVideo="cancelVideo" :videoIndex="1"/>
            <SingleVideo :videoInfo="third" @startRecord="startRecord" @cancelRecord="cancelRecord"
                         @cancelVideo="cancelVideo" :videoIndex="2"/>
            <SingleVideo :videoInfo="fourth" @startRecord="startRecord" @cancelRecord="cancelRecord"
                         @cancelVideo="cancelVideo" :videoIndex="3"/>
        </div>
        <div class="rightList">
            <RightList :data="rightData" @push="push"/>
        </div>
    </div>
</template>

<script>
	import SingleVideo from '@/components/videos/SingleVideo.vue'
	import RightList from "../components/videos/RightList"
	import {getVideoPlayerList, startRecord, stopRecord} from "../request/api"
	import {getItem} from '@/helper/getItem'
	import {setItem} from '@/helper/setItem'

	export default {
		name: 'VideoIndividual',
		components: {
			RightList,
			SingleVideo,
		},
		data() {
			return {
				data: [],
				websock: undefined,
				leftData: [],
				rightData: [],
			}
		},
		async created() {
			await this.initWebSocket()
			await this.webSocketClockSendMsg()
			await this.getVideoList()
		},
		methods: {
			async initWebSocket() {
				const wsUri = process.env.VUE_APP_WS_API + `/webSocket/admin`
				this.websock = new WebSocket(wsUri)
				this.websock.onerror = this.webSocketOnError
				this.websock.onmessage = this.webSocketOnMessage
			},
			webSocketOnError() {
				this.$notify({
					title: 'WebSocket连接发生错误',
					type: 'error',
					duration: 0
				})
			},
			webSocketClockSendMsg() {
				setInterval(() => {
					this.websock.send('ping')
				}, 5000)
			},
			async webSocketOnMessage(e) {
				console.log('调用接口前')
				const res = await getVideoPlayerList()// 设备信息
				console.log('调用接口后')
				this.data = res
				if (e.data === 'pong') {
					// console.log('连接中')
				} else {
					const socketData = JSON.parse(e.data)// 飞行数据
					const id = socketData.data.id
					const code = socketData.msgType.code
					if (code === 0) {
						// 开启新直播
						this.addVideoList(id)
					} else if (code === 1) {
						// 断开直播
						this.deleteVideoList(id)
					} else if (code === 2) {
						// 无人机飞行数据 code===2
						this.getFlyData(socketData)
					} else {
						// 无人机经纬度数据 code===3
						// console.log(3)
					}
				}
			},
			// 设置一个定时器发送消息(5s一次)
			async getVideoList() {
				// 首次连接获取所有直播流
				const res = await getVideoPlayerList()
				const left = getItem('video-list')
				if (res.length > 0) {
					if (left) {
						const leftData = JSON.parse(left)
						const resIdArr = res.map(i => i.id)
						const leftIdArr = leftData.map(i => i.id)
						leftIdArr.forEach(i => {
							if (!resIdArr.includes(i)) {
								const leftIndex = leftData.findIndex(j => j.id === i)
								leftData.splice(leftIndex, 1)
								if (leftData.length <= 0) {
									window.localStorage.removeItem('video-list')
								}
							} else {
								const current = res.find(j => j.id === i)
								const currentIndex = res.findIndex(j => j.id === i)
								res.splice(currentIndex, 1, {...current, buttonVisible: false})
							}
						})
						this.leftData = leftData
						this.rightData = res
					} else {
						this.rightData = res
					}
				} else {
					window.localStorage.removeItem('video-list')
				}
			},
			addVideoList(id) {
				// 增加新直播获取新的直播流
				const added = this.data.find(i => i.id === id)
				this.rightData.push({...added, buttonVisible: true})
			},
			deleteVideoList(id) {
				// 断开直播获取新的视频流
				const rightIndex = this.rightData.findIndex(i => i.id === id)
				this.rightData.splice(rightIndex, 1)
				this.leftData.forEach(i => {
					if (i.id === id) {
						const leftIndex = this.leftData.findIndex(i => i.id === id)
						this.leftData.splice(leftIndex, 1)
						this.deleteLocalVideo(id)
					}
				})
			},
			getFlyData(socketData) {
				const index = this.leftData.map(i => i.id).indexOf(socketData.data.id)
				if (index !== -1) {
					const selected = this.leftData[index]
					// Object.assign数据更新给子的watch deep监听
					Object.assign(this.leftData[index], {
						pullUrl: selected.pullUrl,
						id: selected.id,
						droneName: selected.droneName, // 飞行器名称
						userName: selected.userName, // 管理后台账号
						remainPercent: socketData.data.batteryData.remainPercent, // 飞行器电池电量
						horizontalSpeed: socketData.data.attitudeData.horizontalSpeed, // 水平速度
						verticalSpeed: socketData.data.attitudeData.verticalSpeed, // 垂直速度
						height: socketData.data.attitudeData.height // 高度
					})
				}
			},
			deleteLocalVideo(id) {
				const localVideo = JSON.parse(getItem('video-list'))
				const localIndex = localVideo.findIndex(i => i.id === id)
				localVideo.splice(localIndex, 1)
				if (localVideo.length <= 0) {
					window.localStorage.removeItem('video-list')
					return
				}
				setItem('video-list', JSON.stringify(localVideo))
			},
			// 点击查看直播
			push(res) {
				this.leftData.push(res)
				// pullUrl: res.pullUrl,
				// 	id: res.id,
				// 	droneName: res.droneName,
				// 	userName: res.userName,
				// 	remainPercent: 0,
				// 	horizontalSpeed: 0,
				// 	verticalSpeed: 0,
				// 	height: 0,
				// 	status: 0
				setItem('video-list', JSON.stringify(this.leftData))
			},
			// 取消直播
			cancelVideo(res) {
				const leftIndex = this.leftData.findIndex(i => i.id === res.id)
				const rightIndex = this.rightData.findIndex(i => i.id === res.id)
				this.leftData.splice(leftIndex, 1)
				this.rightData[rightIndex].buttonVisible = true
				this.deleteLocalVideo(res.id)
			},
			async startRecord(e) {
				const {id, index} = e
				try {
					await startRecord({id})
					this.leftData[index].status = 1
				} catch (e) {
					// console.log(e)
				}
			},
			async cancelRecord(e) {
				const {id, index} = e
				try {
					await stopRecord({id})
					this.leftData[index].status = 0
				} catch (e) {
					// console.log(e)
				}
			},
		},
		computed: {
			first() {
				return this.leftData[0] ? this.leftData[0] : null
			},
			second() {
				return this.leftData[1] ? this.leftData[1] : null
			},
			third() {
				return this.leftData[2] ? this.leftData[2] : null
			},
			fourth() {
				return this.leftData[3] ? this.leftData[3] : null
			}
		}
	}
</script>

<style scoped lang="scss">
    @import "src/style/videos";

</style>
